<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { queryAllApi, addApi, queryByIdApi, updateApi, deleteApi } from '@/api/dept.js';
import { ElMessage, ElMessageBox  } from 'element-plus';

const search = async () => {
  // const result = await axios.get('https://apifoxmock.com/m1/3128855-1224313-default/depts');
  // if (result.data.code) {
  //   deptList.value = result.data.data;
  // }
  const result = await queryAllApi();
  if (result.code) {
    deptList.value = result.data;
  }
}

//定义数据模型 - 列表展示
const deptList = ref([]);
//定义钩子函数
onMounted(() => {
  search();
})

//新增/修改部门
const dialogFormVisible = ref(false);
const formTitle = ref('');
const dept = ref({ name: '' });

//新增部门
const add = () => {
  //重置表单校验信息 resetFields()
  if (deptFormRef.value){
    deptFormRef.value.resetFields()
  }

  dialogFormVisible.value = true;
  formTitle.value = '新增部门';
  dept.value = { name: '' };
}

//定义表单校验规则
const deptFormRef = ref();
const rules = ref({
  name: [
    { required: true, message: '部门名称为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '部门名称必须得在2-10位之间', trigger: 'blur' }
  ]
})


//保存部门
const save = async () => {
  //保存之前，先校验表单，校验通过，再发送请求
  if (!deptFormRef) return
  await deptFormRef.value.validate(async (valid, fields) => {
    if (valid) { //通过
      //判断是否有id，如果有id，执行修改
      let result;
      if (dept.value.id) {
        result = await updateApi(dept.value);
      }else{
        result = await addApi(dept.value);
      }
      if (result.code) {//成功
        //弹出一个提示框
        ElMessage.success('保存成功');
        dialogFormVisible.value = false;
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else { //不通过
      ElMessage.error('表单校验不通过，请检查表单');
    }
  })
}

//编辑
const edit = async (id) => {
  const result = await queryByIdApi(id);
  if(result.code){
    dialogFormVisible.value = true;
    dept.value = result.data;
    formTitle.value = '修改部门';
  }
}

//删除
const deleteById = (id) => {
  ElMessageBox.confirm(
    '您确定要删除这条数据吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => { //确认
      const result = await deleteApi(id);
      if (result.code) {
        ElMessage.success('删除成功');
        search();
      }
    })
    .catch(() => { //取消
      ElMessage.info('操作已取消');
    })
}
</script>

<template>
  <!-- 标题 -->
   <!-- <h1>main添加了标题</h1> -->
   <!-- <h1>h1添加了标题</h1> -->
  <h1>部门管理</h1>
  <!-- 按钮 -->
  <div id="header">
    <el-button type="primary" @click="add">+新增部门</el-button>
  </div>
  <!-- 表格 -->
  <el-table :data="deptList" border style="width: 100%">
    <el-table-column type="index" label="序号" width="200" align="center" />
    <el-table-column prop="name" label="部门名称" width="300" align="center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="300" align="center" />
    <el-table-column prop="address" label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增/修改部门的表单 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500">
    <el-form :model="dept" :rules="rules" ref="deptFormRef">
      <el-form-item label="部门名称" label-width="100px" prop="name">
        <el-input v-model="dept.name" placeholder="请输入部门名称，长度2-10位" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
#header {
  margin: 20px 0px;
}
</style>
